<?php

namespace app\api\model;

use app\admin\model\Config;
use app\common\model\MemberToken;
use app\common\model\Token;
use app\exceptions\ApiException;
use EasyWeChat\Factory;
use think\cache\driver\Redis;
use think\Exception;
use think\Model;

/**
 * Member
 */
class Member extends Model
{
    // 表名
    protected $name = 'member';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    protected $updateTime = false;
    protected $expire_time = 60;

    // 字段类型转换
    protected $type = [
        'login_time' => 'timestamp:Y-m-d H:i:s',
    ];


    public function wxLogin($params)
    {
        $iv = $params['iv'] ?? '';
        $encryptedData = $params['encryptedData'] ?? '';
        $code = $params['code'] ?? '';
        $uniqid = $params['uniqid'] ?? '';
        if (!$code || !$iv || !$encryptedData) {
            throw  new ApiException('参数错误');
        }
        // 获取授权appid
        $app = Factory::miniProgram(config('wechat.xcx'));
        $data = $app->auth->session($params['code']);
        if (!$data) {
            throw new ApiException('登录异常');
        }
        $session = $data['session_key'] ?? '';
        if (!$session) {
            throw new ApiException('登录失败');
        }
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptedData);
        $phone = $decryptedData['phoneNumber'] ?? '';
        if (!$phone) {
            throw new ApiException('获取手机号失败');
        }

        $userInfo = self::where(['phone' => $phone])->find();
        if (!$userInfo) {
            //用户不存在，创建用户
            $last_four_digits = substr($phone, -4);
            $insert['nickname'] = $params['nickName'] ?? '天民田园_' . $last_four_digits;
            $insert['openid'] = $data['openid'];
            $insert['create_time'] = time();
            $insert['login_time'] = time();
            $insert['phone'] = $phone ?? '';
            $userId = (new Member())->save($insert);
        } else {
            if ($userInfo['status'] == 0) {
                throw new ApiException('您的账号已被封禁');
            }
            $userId = $userInfo['id'];
            (new Member())->where(['id' => $userId])->update(['login_time' => time()]);
        }

        $wxUserMes['user_token'] = (new Token())->product_token($userId, 1);
        //获取用户信息
        $wxUserMes['uid'] = $userId;
        if ($uniqid) {
            $this->saveRedis($wxUserMes, $uniqid);
        }
        return api_message($wxUserMes, '登录成功');
    }


    public function updateUser($params)
    {
        $avatar = $params['avatar'] ?? '';
        $nickname = $params['nickname'] ?? '';
        if (!$avatar) {
            throw new ApiException('请填上传头像');
        }

        if (!$nickname) {
            throw new ApiException('请填写昵称');
        }
        $avatar = $this->removeDomain($avatar);

        if (!self::where(['id' => $params['member_id']])->update(['nickname' => $nickname,'avatar' => $avatar])) {
            throw new ApiException('修改失败');
        }
        return api_message([], '修改成功');
    }


    public   function removeDomain($url)
    {
        if (strpos($url, "https://") === 0 || strpos($url, "http://") === 0) {
            // 分割 URL 来去除 https://
            $urlParts = explode('/', $url, 4); // 最多分割成四部分
            if (count($urlParts) > 3) {
                // 重新构建 URL，排除协议和域名部分
                return '/' . $urlParts[3];
            }
        }
        return $url; // 如果 URL 不以 https:// 开头，直接返回
    }


    public function saveRedis($user, $uniqid)
    {
        $redis = new Redis();
        $redis->set($uniqid, $user, $this->expire_time);
    }


    public function getUser($params)
    {
        $member_id = $params['member_id'] ?? '';
        $member = self::where(['id' => $member_id])
            ->field('id,nickname,avatar,phone,total_integral,residue_integral')
            ->find();
        $member['phone'] = $this->maskPhoneNumber($member['phone']);
        if (!$member['avatar']) {
            $defaultAvatar = (new \app\common\model\Config())->where(['name' => 'avatar'])->value('value');
            $member['avatar'] = env('domain.image_url') . $defaultAvatar;
        }else{
            $member['avatar'] = env('domain.image_url') . $member['avatar'];
        }

        return api_message($member);
    }

    public function maskPhoneNumber($phoneNumber)
    {
        // 获取前三位数字
        $prefix = substr($phoneNumber, 0, 3);
        // 获取手机号最后四位数字
        $suffix = substr($phoneNumber, -4);
        // 获取手机号长度
        $length = strlen($phoneNumber);

        // 计算需要替换为星号的位数
        $maskLength = $length - 7;

        // 将中间的数字替换为 "*"
        $masked = $prefix . str_repeat('*', $maskLength) . $suffix;

        return $masked;
    }


    public function loginOut($params){
        if(!(new MemberToken())->where(['id' => $params['member_id']])->delete()){
            throw new ApiException('操作失败');
        }
        return api_message([],'退出成功');
    }

}